<script lang="ts" setup>
import { ref, defineExpose, defineEmits, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'

const emit = defineEmits(['enterKey', 'cancel'])

// 接收父组件传递的初始值
const props = defineProps<{
  initialValue?: string
}>()

const isFocus = ref(false)
const inputValue = ref(props.initialValue) // 初始化为父组件传递的值

// 监听initialValue变化，更新inputValue
watch(() => props.initialValue, (newVal) => {
  inputValue.value = newVal
})

// 统一处理获取焦点（兼容 H5/APP/小程序）
const focusInput = () => {
    isFocus.value = true

    // 在小程序中，可能需要延迟触发以确保生效
    // #ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
    setTimeout(() => {
        isFocus.value = false
        setTimeout(() => {
            isFocus.value = true
        }, 50)
    }, 300)
    // #endif
}

// 回车时触发搜索
const onEnterKey = (event: any) => {
    const keyword = event.detail.value?.trim() || inputValue.value?.trim()
    if (keyword) {
        emit('enterKey', keyword)
        // 注意：这里不再清空inputValue，因为可能需要保留显示
    }
}

// 取消按钮
const onCancel = () => {
    emit('cancel')
}

// 暴露方法给父组件
defineExpose({
    onEnterKey,
    getInputValue: () => inputValue.value,
    setInputValue: (value: string) => { inputValue.value = value },
    focus: focusInput
})

// 初始化时自动聚焦
onShow(() => {
    focusInput()
})
</script>

<template>
    <!-- 搜索框 -->
    <view class="input">
        <view class="input-input">
            <input :value="inputValue" :focus="isFocus" @confirm="onEnterKey" type="text"
                placeholder="请输入关键词"  @touchend.prevent="focusInput" confirm-type="search" 
                @input="(e:any) => inputValue = e.detail.value"/>
        </view>
        <view class="input-text" @click="onCancel">取消</view>
    </view>
</template>

<style lang="scss" scoped>
// 输入框样式
.input {
    display: flex;
    align-items: center;
    justify-content: space-between;

    &-input {
        width: 80%;
        background-color: $uni-bg-color;
        border-radius: $uni-border-radius;
        padding: 25rpx;
    }

    &-text {
        color: #a0a2a2;
    }
}
</style>